package com.child.config;

import com.child.controller.ChildBean;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * com.child.config.ChildConfiguration
 *
 * @author: wanglei62
 * @DATE: 2022/10/17 15:18
 **/
@Configuration
@ComponentScan("com.child")
@MapperScan(basePackages = "com.child.mapper")
public class ChildConfiguration {


    private static final String XML_MAPPER_LOAD_PATH = "classpath*:mapper/**/*.xml";

    /**
     * XML Mapper 列表
     */
    private static final List<String> XML_FILE_LIST = Arrays.asList(
            "mapper/com/child/mapper/MyUserMapper.xml");

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public ChildBean childBean(){
        ChildBean cb = new ChildBean();
        cb.setName("testChildBean");
        return cb;
    }


    @PostConstruct
    public void additionalXMLMapperResourceInit() {
        try {
            SqlSessionFactory factory = applicationContext.getBean(SqlSessionFactory.class);

            org.apache.ibatis.session.Configuration configuration = factory.getConfiguration();
//            configuration.addMappers("com.child.mapper");

            addXMLMappers(configuration);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addXMLMappers(org.apache.ibatis.session.Configuration configuration) throws IOException {
        for (String xmlFileName : XML_FILE_LIST) {
            // XML 解析器构造
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
                    Resources.getResourceAsStream(xmlFileName),
                    configuration,
                    XML_MAPPER_LOAD_PATH,
                    configuration.getSqlFragments());

            // 解析并注入 mapper工厂
            xmlMapperBuilder.parse();
        }
    }

}
